package com.smart.smartdata;

import static com.inuker.bluetooth.library.Constants.REQUEST_SUCCESS;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;

import com.inuker.bluetooth.library.connect.response.BleConnectResponse;
import com.inuker.bluetooth.library.connect.response.BleNotifyResponse;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.search.SearchResult;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.jude.easyrecyclerview.decoration.SpaceDecoration;
import com.smart.smartdata.adapters.BleAdapter;
import com.smart.smartdata.ble.BleDevice;
import com.smart.smartdata.ble.ClientManager;
import com.smart.smartdata.ble.IBeaconRecord;
import com.smart.smartdata.ble.SPO2BleManager;
import com.smart.smartdata.ble.TemperatureBleManager;
import com.smart.smartdata.eventbus.EventBus;
import com.smart.smartdata.eventbus.EventNames;

import java.util.List;
import java.util.UUID;

import butterknife.Bind;
import butterknife.ButterKnife;


public class ScanBleActivity extends AppCompatActivity {
    @Bind(R.id.recyclerView)
    EasyRecyclerView recyclerView;

    BleAdapter mBleAdapter;
    BluetoothAdapter mBle;
    String type;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_ble);
        StatusBarUtil.setRootViewFitsSystemWindows(this, false);
        StatusBarUtil.setTranslucentStatus(this);//透明状态栏
        ButterKnife.bind(this);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null && bundle.containsKey("type")) {
            type = bundle.getString("type");
        }

        mBle = BluetoothAdapter.getDefaultAdapter();
        mBleAdapter = new BleAdapter(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        SpaceDecoration decoration = new SpaceDecoration(DeviceUtils.dp2px(10));
        decoration.setPaddingEdgeSide(false);
        decoration.setPaddingStart(false);
        recyclerView.addItemDecoration(decoration);
        recyclerView.setAdapter(mBleAdapter);
        mBleAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                ClientManager.getClient().connect(mBleAdapter.getAllData().get(position).getMac(), new BleConnectResponse() {
                    @Override
                    public void onResponse(int code, BleGattProfile profile) {
                        if (code == REQUEST_SUCCESS) {
                            Log.e("连接设备：", "蓝牙连接成功");
                            AppUtils.toastShort(ScanBleActivity.this, "连接成功");
                            if("spo2".equals(type)){
                                SPO2BleManager.getInstance().setBleDevice(mBleAdapter.getAllData().get(position));
                            }else if("temperature".equals(type)){
                                TemperatureBleManager.getInstance().setBleDevice(mBleAdapter.getAllData().get(position));
                            }
                            EventBus.getInstance().notifiDataUpdate(EventNames.CONNECT_SUCCESS, type);
                            finish();
                        }
                    }
                });
            }
        });
        initBle();
    }


    private void link() {
        SPO2BleManager.getInstance().openNotify(SPO2BleManager.getInstance().getBleDevice().getMac(), new BleNotifyResponse() {
            @Override
            public void onNotify(UUID service, UUID character, byte[] value) {
                String result = ByteUtil.toHexString(value).replace(" ", "");
                Log.e("应答命令：", result);
                int spo2 = Integer.parseInt(result, 16);
                Log.e("血氧饱和度：", spo2 + "");
            }

            @Override
            public void onResponse(int code) {

            }
        });

//        TemperatureBleManager.getInstance().openNotify(TemperatureBleManager.getInstance().getBleDevice().getMac(), new BleNotifyResponse() {
//            @Override
//            public void onNotify(UUID service, UUID character, byte[] value) {
//                String result = ByteUtil.toHexString(value).replace(" ", "");
//                Log.e("应答命令：", result);
//                result = result.substring(6, 8) + result.substring(4, 6) + result.substring(2, 4) + result.substring(0, 2);
//                Log.e("转换命令：", result);
//                String temperature = String.format("%.1f", Integer.parseInt(result, 16) / 10000.0);
//                Log.e("体温：", temperature);
//            }
//
//            @Override
//            public void onResponse(int code) {
//
//            }
//        });
//        String results = "#setConfigMode:521654$";
//        Log.e("连接设备mac", BleManager.getInstance().getBleDevice().getMac() + "");
//        BleManager.getInstance().writeCharacteristic(BleManager.getInstance().getBleDevice().getMac(), results.getBytes(), new BleWriteResponse() {
//            @Override
//            public void onResponse(int code) {
//                Log.e("连接设备：", "返回码" + code);
//                if (code == 0) {
//                    finish();
//                }
//            }
//        });
    }

    private void initBle() {
        searchBle();
    }

    private void searchBle() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            if (mBle != null && mBle.isEnabled()) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mBle.stopLeScan(leScanCallback);
                    }
                }, 3 * 1000);
                mBle.startLeScan(leScanCallback);
            }
        }
    }

    BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            IBeaconRecord record = new IBeaconRecord();
            if (ByteUtil.fromScanData(scanRecord, record)) {
                String address = device.getAddress(); // 获取Mac地址
                String name = device.getName(); // 获取设备名称
                String key = name + "_" + address;
                record.address = address; // Mac地址
                record.rssi = rssi; // 场强
            }

            SearchResult result = new SearchResult(device, rssi, scanRecord);
            if (device != null && result.getName() != "NULL" && device.getName() != null &&
                    !deviceContains(mBleAdapter.getAllData(), result)) {
                mBleAdapter.add(new BleDevice(result.getName(), result.getAddress()));
            }
            mBleAdapter.notifyDataSetChanged();
        }
    };

    private boolean deviceContains(List<BleDevice> list, SearchResult nDevice) {
        if (!list.isEmpty()) {
            for (int i = 0; i < list.size(); i++) {
                BleDevice device = list.get(i);
                String s = device.getName();
                String s1 = nDevice.getName();
                if (device.getName().equals(nDevice.getName())) {
//                    if (device.getSearchResult().getAddress() == nDevice.getAddress()){
                    return true;
                }
            }
        }
        return false;
    }

}
